# gozerbot/nextid.py
#
#

""" provide increasing counters """

__copyright__ = 'this file is in the public domain'

from gozerbot.datadir import datadir
from gozerbot.persist import Persist

class Nextid(Persist):

    """ counters by name """

    def __init__(self, fname):
        Persist.__init__(self, fname)
        if not self.data:
            self.data = {}

    def get(self, item):
        """ get counter for item """
        item = item.lower()
        try:
            result = self.data[item]
        except KeyError:
            return None 
        return result

    def set(self, item, number):
        """ set counter of item to number """
        item = item.lower()
        try:
            self.data[item] = int(number)
        except ValueError:
            return 0
        self.save()
        return 1

    def next(self, item):
        """ get increment of item counter """
        item = item.lower()
        try:
            self.data[item] += 1
        except:
            self.data[item] = 1
        self.save()
        return self.data[item]

nextid = Nextid(datadir + '/nextid')
